(function () {
  "use strict";

  document.addEventListener("DOMContentLoaded", (event) => {
    let connectButton = document.querySelector("#connect");
    let statusDisplay = document.querySelector("#status");
    let port;
    // 记录执行过的命令
    function addLine(linesId, text) {
      var senderLine = document.createElement("div");
      senderLine.className = "line";
      var textnode = document.createTextNode(text);
      senderLine.appendChild(textnode);
      document.getElementById(linesId).appendChild(senderLine);
      return senderLine;
    }

    let currentReceiverLine;

    function appendLines(linesId, text) {
      const lines = text.split("\r");
      if (currentReceiverLine) {
        currentReceiverLine.innerHTML =
          currentReceiverLine.innerHTML + lines[0];
        for (let i = 1; i < lines.length; i++) {
          currentReceiverLine = addLine(linesId, lines[i]);
        }
      } else {
        for (let i = 0; i < lines.length; i++) {
          currentReceiverLine = addLine(linesId, lines[i]);
        }
      }
    }
    // 手动连接
    function connect() {
      port.connect().then(
        () => {
          statusDisplay.textContent = "";
          connectButton.textContent = "Disconnect";
          // 监听数据
          port.onReceive = (data) => {
            let textDecoder = new TextDecoder();
            console.log(textDecoder.decode(data));
            if (data.getInt8() === 13) {
              currentReceiverLine = null;
            } else {
              appendLines("receiver_lines", textDecoder.decode(data));
            }
          };
          port.onReceiveError = (error) => {
            console.error(error);
          };
        },
        (error) => {
          statusDisplay.textContent = error;
        }
      );
    }
    // 监听连接或者断开连接
    connectButton.addEventListener("click", function () {
      if (port) {
        port.disconnect();
        connectButton.textContent = "Connect";
        statusDisplay.textContent = "";
        port = null;
      } else {
        serial
          .requestPort()
          .then((selectedPort) => {
            port = selectedPort;
            connect();
          })
          .catch((error) => {
            statusDisplay.textContent = error;
          });
      }
    });
    // 自动获取连接过的设备
    serial.getPorts().then((ports) => {
      if (ports.length === 0) {
        statusDisplay.textContent = "No device found.";
      } else {
        statusDisplay.textContent = "Connecting...";
        port = ports[0];
        connect();
      }
    });
    // 命令输入Input元素
    let commandLine = document.getElementById("command_line");
    // 监听Enter回车按键
    commandLine.addEventListener("keypress", function (event) {
      if (event.keyCode === 13) {
        if (commandLine.value.length > 0) {
          addLine("sender_lines", commandLine.value);
          commandLine.value = "";
        }
      }
      // 发送数据
      port.send(
        new TextEncoder("utf-8").encode(
          String.fromCharCode(event.which || event.keyCode)
        )
      );
    });
  });
})();
